package org.afk.tools.com;

import java.util.*;

public class Arguments
{
	private final HashMap<String, String> arguments = new HashMap<String, String>();

	public Arguments(final String[] args)
	{
		int position = 0;
		for (;;)
		{
			if (position >= args.length)
				break;

			if (args[position].startsWith("-"))
				position = addKeyedValue(args, position);
			else
				addValueArgument(args, position);

			position++;
		}
	}

	private void addKeyArgument(final String key)
	{
		this.arguments.put(key, "");
	}

	private int addKeyedValue(final String[] args, int position)
	{
		final String key = parseKey(args[position]);
		if (isNextParameterValue(args, position))
			addKeyValueArgument(args, ++position, key);
		else
			addKeyArgument(key);
		return position;
	}

	private void addKeyValueArgument(final String[] args, final int position, final String key)
	{
		this.arguments.put(key, args[position]);
	}

	private void addValueArgument(final String[] args, final int position)
	{
		this.arguments.put(Integer.toString(position + 1), args[position]);
	}

	private boolean isNextParameterValue(final String[] args, final int i)
	{
		return ((i + 1) < args.length) && !args[i + 1].startsWith("-");
	}

	private String parseKey(final String keyParameter)
	{
		if (keyParameter.length() > 1)
			return keyParameter.substring(1);
		return keyParameter;
	}

	public String get(final String key)
	{
		return this.arguments.get(key);
	}

	public boolean hasArgument(final String test)
	{
		return this.arguments.containsKey(test);
	}

	@Override
	public String toString()
	{
		return "Arguments [arguments=" + this.arguments + "]";
	}

}
